import {Component, OnInit, ViewChild} from '@angular/core';
import {ActionPanelComponent} from '../../components/action-panel/action-panel.component';
import {ActivatedRoute} from '@angular/router';
import {ConfigService} from '../../services/config.service';
import {AlertController, Events, ModalController, NavController, ToastController} from '@ionic/angular';
import {BasePage} from '../../common/basePage';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {HttpService} from '../../services/http.service';
import {AppConfig} from '../../common/app-config.enum';
import {Storage} from '@ionic/storage';
import {switchMap} from 'rxjs/internal/operators';
import {Observable, of} from 'rxjs';
import {RedpacketListComponent} from '../../components/redpacket-list/redpacket-list.component';
import {IframePageComponent} from '../../components/iframe-page/iframe-page.component';
import {RegistryAgreementComponent} from '../../components/registry-agreement/registry-agreement.component';

/**
 * 标的信息(投资)
 */
@Component({
  selector: 'app-bid',
  templateUrl: './bid.page.html',
  styleUrls: ['./bid.page.scss'],
})
export class BidPage extends BasePage implements OnInit {

  public bid: any = {};
  public investExpireTime: any = null;
  public canPerchaseAmout = 0;
  // 获取计算器组件实例
  @ViewChild('calculatorPanel') calculatorPanel: ActionPanelComponent;
  // 获取投资组件实例
  @ViewChild('purchasePanel') purchasePanel: ActionPanelComponent;
  // 进度条相关属性
  public progress: number;
  public knob_left: any = {'left': '0'};
  public bar_right: any = {'right': '100%'};
  // 是否为定向标
  welfareTable = false;
  // 定向标密码
  password = null;
  // 账户余额
  userBalance: number;
  // 最大可投金额
  maxPurchase: number;
  // 用户投资金额
  investAmt: number;
  // 预售倒计时
  bidCountDown = 0;
  // setInterval标识
  interval: number;
  // 系统允许投资上下限值
  sysInvestAmt = {};
  // 红包列表
  redpackets: any[] = null;
  // 加息券列表
  coupons: any[] = null;
  // 当前使用的红包或加息券
  currGrant = null;
  // 协议内容
  investAgrees: any = {};
  // 是否同意协议
  isAgree = false;
  // 返回地址
  from: string;

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private alertCtrl: AlertController,
              private events: Events,
              private routeInfo: ActivatedRoute,
              private configService: ConfigService,
              private service$: HttpService,
              private storage: Storage,
              private modalCtrl: ModalController
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    this.getData();
  }

  // 获取标的信息
  private getData() {
    this.from = this.routeInfo.snapshot.params['from'] || '/tabs/home';
    // 获取标的信息
    this.service$.doRequest(UrlAndOPT.bid_bid, {
      bidIdSign: this.routeInfo.snapshot.params['bidIdSign']
    })
      .subscribe(obj => {
        if (obj) {
          this.bid = obj['bidInfo'];
          this.welfareTable = obj['welfareTable'];
          // 计算可投金额
          this.canPerchaseAmout = Math.floor(this.bid['amount'] - this.bid['hasInvestedAmount']);
          // 获取截止日期
          this.investExpireTime = this.bid['investExpireTime']['time'];
          // 获取倒计时毫秒数
          this.bidCountDown = this.bid['preDate']['time'] - obj['nowTime']['time'];
          if (this.bidCountDown > 0) { // 预发布时间晚于当前时间
            this.interval = setInterval(() => {
              if (this.bidCountDown < 1000) {
                this.bidCountDown = 0;
                clearInterval(this.interval);
              } else {
                this.bidCountDown -= 1000;
              }
            }, 1000);
          }
          // 执行进度动画
          setTimeout(() => {
            this.changeProgress(this.bid['loanSchedule']);
          }, 50);
        }
      });
  }

  // 进度条动画
  changeProgress(schedule) {
    this.knob_left = {'left': schedule + '%'};
    this.bar_right = {'right': (100 - schedule) + '%'};
  }

  // 打开计算器
  openCalculator() {
    this.calculatorPanel.showActionPanel();
  }

  // 关闭计算器
  closeCalculator() {
    this.calculatorPanel.hideActionPanel();
  }

  // 打开投资面板
  async openPurchase() {
    const userInfo = await this.storage.get(AppConfig.USER_INFO);
    // 判断是否登录
    if (userInfo && userInfo[AppConfig.USER_INFO_KEY]) {
      if (userInfo[AppConfig.USER_ROLE_KEY]) { // 判断是否有角色
        if (userInfo[AppConfig.USER_ROLE_KEY] === 1) { // 如果角色为出借人
          this.prePurchase(); // 准备标的信息
        } else { // 角色为借款人
          this.showToast('借款人不能进行出借投资');
        }
      } else { // 无角色前往实名认证
        this.service$.doUndo(1, {step: '实名认证'});
      }
    } else { // 未登录前往登录页
      this.service$.clearUserInfo()
        .then(() => {
          this.navCtrl.navigateForward('/login');
        });
    }
  }

  // 请求标的准备信息
  private prePurchase() {
    this.service$.doRequest(UrlAndOPT.auth_purchase_pre, {bidIdSign: this.bid['bidIdSign']})
      .pipe(
        switchMap(res => {
          if (res) {
            const obj = res['obj'];
            // 出借前置流程存在缺失
            if (obj['undoList'] && obj['undoList'].length > 0) {
              // 查找优先级最高的缺失步骤
              let undo;
              obj['undoList'] = obj['undoList'].map(undoObj => undoObj['code']);
              loop: for (let i = 0; i < this.service$.undoList.length; i++) {
                for (const code of obj['undoList']) {
                  if (this.service$.undoList[i]['code'] === code) {
                    undo = this.service$.undoList[i];
                    break loop;
                  }
                }
              }
              // 流程补办
              this.service$.doUndo(1, undo);
              return of(false);
            } else {
              return this.setPurchaseAndGetFunc(obj);
            }
          }
          return of(res);
        })
      )
      .subscribe(obj => {
        if (obj) {
          // 获取账户余额
          this.userBalance = obj['userFundInfo']['balance'];
          // 用户可投最大金额限制
          this.maxPurchase = Math.floor(Math.min(this.userBalance, this.canPerchaseAmout, this.sysInvestAmt['maxInvestAmt']));
          // 打开投资面板
          this.showPurchasePanel();
          // 判断是否为定向标
          // this.isWelfareTable();
        }
      });
  }

  // 设置投资信息，获取用户数据
  private setPurchaseAndGetFunc(obj: any): Observable<any> {
    // 保存系统投资上下限值
    this.sysInvestAmt = {minInvestAmt: obj['minInvestAmt'], maxInvestAmt: obj['maxInvestAmt']};
    // 保存红包和加息券信息
    this.redpackets = obj['redpackets'];
    this.coupons = obj['coupons'];
    this.investAgrees = obj['investAgrees'][0];
    // 获取用户基础数据和账户数据
    return this.service$.doRequest(UrlAndOPT.auth_userInfo_func, {userRole: 1});
  }

  // 定向标判断
  private async isWelfareTable() {
    if (this.welfareTable) { // 如为定向标，打开密码输入框
      await this.presentAlertPrompt();
    } else {
      this.showPurchasePanel(); // 否则直接打开投资面板
    }
  }

  // 打开密码输入框
  private async presentAlertPrompt() {
    const alert = await this.alertCtrl.create({
      subHeader: '此标的为定向标，请输入密码',
      inputs: [
        {
          name: 'password', // 读取值时，作为键名
          type: 'text',
          placeholder: '输入密码'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        }, {
          text: '确定',
          handler: value => {
            // 读取密码值(键名与输入框的name对应)
            this.password = value['password'];
            // 点击确定后打开投资面板
            this.showPurchasePanel();
          }
        }
      ]
    });
    await alert.present();
  }

  // 显示投资面板
  private showPurchasePanel() {
    // 初始化投资数据
    this.currGrant = null;
    this.investAmt = null;
    this.isAgree = false;
    this.purchasePanel.showActionPanel();
  }

  // 关闭投资面板
  closePurchase() {
    this.purchasePanel.hideActionPanel();
  }

  // 全部投资
  allPurchase() {
    this.investAmt = this.maxPurchase;
  }

  // 控制输入的内容
  amountInput($event) {
    if ($event.target.value) {
      const val = $event.target.value.replace(/\D/g, '');
      if (val) {
        if (/^[1-9][0-9]*$/.test(val)) {
          $event.target.value = val > this.maxPurchase ? this.maxPurchase : val;
        } else {
          $event.target.value = null;
        }
      }
    } else {
      $event.target.value = null;
    }
    if (this.currGrant && (!this.investAmt || this.currGrant['invest_amt'] > this.investAmt)) {
      const typeName = this.currGrant['apr'] ? '加息券' : '红包';
      this.showToast('投资金额不符合' + typeName + '使用限制，已取消！');
      this.currGrant = null;
    }
  }

  // 打开红包或加息券列表
  async openRedpackets(type: 'redpackets' | 'coupons') {
    if (this[type] && this[type].length > 0) {
      let flag = false;
      // 判断已选优惠与点选类型是否一致
      if (this.currGrant && ((this.currGrant['apr'] && type === 'redpackets') || (!this.currGrant['apr'] && type === 'coupons'))) {
        flag = true;
      }
      if (flag) {
        // 若类型不一致，给出提示
        const alert = await this.alertCtrl.create({
          header: '提示',
          message: '红包与加息券不可同时使用，确定要替换当前所选优惠类型吗？',
          buttons: [
            {
              text: '不替换',
              role: 'cancel'
            }, {
              text: '确定',
              handler: () => {
                this.openModel(type);
              }
            }
          ]
        });
        await alert.present();
      } else {
        // 类型一致打开model
        this.openModel(type);
      }
    }
  }

  // 打开红包列表model
  async openModel(type: 'redpackets' | 'coupons') {
    const modal = await this.modalCtrl.create({
      component: RedpacketListComponent,
      componentProps: {
        title: type === 'redpackets' ? '红包' : '加息券',
        list: this[type],
        investAmt: this.investAmt
      }
    });
    await modal.present();
    const {data} = await modal.onDidDismiss();
    if (data) {
      this.currGrant = data['grant'];
    }
  }

  // 打开协议
  async openAgreement() {
    const modal = await this.modalCtrl.create({
      component: RegistryAgreementComponent,
      componentProps: {
        title: this.investAgrees['title'],
        html: this.investAgrees['content']
      }
    });
    return await modal.present();
  }

  // 执行投资
  async doPurchase() {
    if (!this.isAgree) {
      this.showToast('请勾选出借协议');
    } else if (!this.investAmt || this.investAmt < this.sysInvestAmt['minInvestAmt'] || this.investAmt > this.maxPurchase) {
      this.showToast('投资金额不符合要求（' + this.sysInvestAmt['minInvestAmt'] + '至' + this.maxPurchase + '元）');
    } else {
      // 获取优惠金额
      let cardVocherAmount = 0;
      // 如果使用了优惠并且为红包，则优惠金额为红包金额(加息券不参与直接计算)
      if (!!this.currGrant && !this.currGrant['apr']) {
        cardVocherAmount = this.currGrant['amount'];
      }
      const params: any = {
        investAmt: this.investAmt - cardVocherAmount, // 实际支付金额等于投资金额减去优惠金额
        bidIdSign: this.bid['bidIdSign'],
        cardVocherSign: this.currGrant ? this.currGrant['sign'] : null, // 红包或加息券ID
        cardVocherType: !this.currGrant ? 0 : this.currGrant['apr'] ? 2 : 1, // 优惠类型(红包或加息券)
        password: this.password // 定向标密码
      };
      this.service$.doRequest(UrlAndOPT.bid_invest, params)
        .subscribe(async (obj) => {
          if (obj) {
            // 打开银行投资页面model
            const modal = await this.modalCtrl.create({
              component: IframePageComponent,
              componentProps: {
                title: '出借',
                url: obj['url']
              }
            });
            await modal.present();
            // 关闭model后，发送用户账户变动通知，关闭投资面板，刷新标的信息
            await modal.onDidDismiss();
            this.events.publish(AppConfig.TOPIC_USER_FUNC);
            this.closePurchase();
            this.getData();
          }
        });
    }
  }

  goBack() {
    this.navCtrl.navigateBack([this.from]);
  }

}
